import { Component, OnInit } from '@angular/core';
import { HomeService } from './home.service';
import * as moment from 'moment';
import * as _ from 'lodash'
import * as echarts from 'echarts';
import { environment } from '../../../../environments/environment';
import { DataService } from '../../../services/data.service';
// import { Util } from '../../../common/util';

@Component({
	selector: 'app-home',
	templateUrl: './home.component.html',
	styleUrls: ['./home.component.scss'],
	providers: [HomeService]
})
export class HomeComponent implements OnInit {
	// 字典值post
	public dictionaryPost: any = {
		sItemNos: ''
	};
	// 菜单数据
	public menuData: any;
	// 菜单权限set
	public menuResourceSet: any = [];
	// 字典值
	public dictionaryList: any = {};
	// 托管行字典值
	// public bankDictionaryList: any = [];
	// 右侧公募统计数据
	public publicData = [];
	public publicDataKey = [];
	public publicDataValue = [];
	// 右侧一对多统计数据
	public otmData = [];
	public otmDataKey = [];
	public otmDataValue = [];
	// 右侧一对一统计数据
	public otoData = [];
	public otoDataKey = [];
	public otoDataValue = [];
	// 下方折线图数据
	public lineData = [];
	public lineDataKey = [];
	public lineDataValue = [];


	//updated by dujh @20180704 start
	//保存对首页按钮的权限  还要考虑到安全的情况
	public hasPublic = 0;//对应'tag-home-publicissue'
	public hasOTM = 0;//对应'tag-home-otm'
	public hasOTO= 0;//对应'tag-home-oto'

	//updated by dujh @20180704 start
	constructor(
		private homeService: HomeService,
		public dataService: DataService
	) {

	}

	ngOnInit() {
		let that = this;
		// 权限处理
		// this.dataService.initTree.subscribe((data) => {
		// 	if (data) {
		// 		this.menuResourceSet = [];
		// 		this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '条目录入');
		// 		sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
		// 	}
		// })
		// this.menuResourceSet = [];
		// this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '条目录入');
		// sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
		
		//updated by dujh @20180704 start
		//查找到当前用户首页三个按钮的操作权限 用一个对象表示  对应的字段为1有就表示有该权限
		let menu = JSON.parse(sessionStorage.getItem('menu'));

		if(menu){
			for(let i =0;i<menu.length;i++){
				if(menu[i].sName ==="首页"){
					let temp = menu[i].resourceSet;
					for(var s of temp){
						//如果存在对应的权限则标志为对应的数字  
						//'tag-home-publicissue' ---> 1
						//'tag-home-otm'--->2
						//'tag-home-oto'--->3
						if (s === 'tag-home-publicissue'){
							this.hasPublic = 1;
						}
						if (s === 'tag-home-otm'){
							this.hasOTM = 2;
						}
						if (s === 'tag-home-oto'){
							this.hasOTO = 3;
						}
					}
					// this.A = 0;
					// this.B = 2;
					// this.C = 3;
					break;
				}
			}
		}
		//updated by dujh @20180704 end 
		// 如果关闭单点
		if (this.dataService.hasLoginInfo) {
			// 加载左侧日历
			this.initCalendar();

			//updated by dujh @20180704 start
			// 加载右侧产品统计图
			// this.initCharts(1);
			// console.log(this.A || this.B || this.C);
			this.initCharts(this.hasPublic || this.hasOTM || this.hasOTO);
			//updated by dujh @20180704 end
			// 下方折线图echarts
			this.initeCharts();
			// 字典值
			this.getDictionary();
		}
		// 如果开启单点
		if (environment.isSSO) {
			// 加载左侧日历
			this.initCalendar();
			//updated by dujh @20180704 start
			// 加载右侧产品统计图
			// this.initCharts(1);
			// console.log(this.A || this.B || this.C);
			this.initCharts(this.hasPublic || this.hasOTM || this.hasOTO);
			//updated by dujh @20180704 end
			// 下方折线图echarts
			this.initeCharts();
			// 字典值
			this.getDictionary();
		}

	}

	ngAfterViewInit() {

		// 托管行字典值
		// this.getBankDictionary();

	}

	// 获取字典值
	getDictionary() {
		let that = this;
		this.homeService.getDictionary(this.dictionaryPost).subscribe(data => {
			if (data) {
				that.dictionaryList = data;
				localStorage.setItem("dictionaryList", JSON.stringify(that.dictionaryList));
			}
		})
	};
	// 获取托管行字典值
	// getBankDictionary() {
	// 	let that = this;
	// 	this.homeService.getBankDictionary().subscribe(data => {
	// 		if (data) {
	// 			that.bankDictionaryList = data;
	// 			localStorage.setItem("bankDictionaryList", JSON.stringify(that.bankDictionaryList));
	// 		}
	// 	})
	// };
	// 左侧日历
	initCalendar() {
		window['$'](function () {

			/* initialize the external events
			 -----------------------------------------------------------------*/
			function ini_events(ele) {
				ele.each(function () {

					// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
					// it doesn't need to have a start or end
					var eventObject = {
						title: window['$'].trim(window['$'](this).text()) // use the element's text as the event title
					};

					// store the Event Object in the DOM element so we can get to it later
					window['$'](this).data('eventObject', eventObject);

					// make the event draggable using jQuery UI
					window['$'](this).draggable({
						zIndex: 1070,
						revert: true, // will cause the event to go back to its
						revertDuration: 0  //  original position after the drag
					});

				});
			}

			ini_events(window['$']('#external-events div.external-event'));

			/* initialize the calendar
			 -----------------------------------------------------------------*/
			//Date for the calendar events (dummy data)
			var date = new Date();
			var d = date.getDate(),
				m = date.getMonth(),
				y = date.getFullYear();
			window['$']('#calendar').fullCalendar({
				aspectRatio: 3,
				contentHeight: 319,
				fixedWeekCount: false,
				header: {
					left: 'prev,next today',
					center: 'title',
					right: ''
				},
				buttonText: {
					today: '今天'
					// month: '月',
					// week: '周',
					// day: '日'
				},
				// 点击事件
				eventClick: function (calEvent, jsEvent, view) {
					window['$']("#calender-modal").modal('show');
					// alert('Event: ' + calEvent.title);
					// alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
					// alert('View: ' + view.name);

					// change the border color just for fun
					// window['$'](this).css('border-color', 'red');

				},
				//Random default events
				events: [
					// {
					// 	title: '产品过期提醒',
					// 	start: '2018-01-02',
					// 	backgroundColor: "rgb(30,185,225)",
					// 	borderColor: "rgb(30,185,225)"
					// }
					// ,
					// {
					// 	title: ' 5',
					// 	start: new Date(y, m, d - 5),
					// 	backgroundColor: "rgb(30,185,225)",
					// 	borderColor: "rgb(30,185,225)"
					// }, {
					// 	title: ' 3',
					// 	start: new Date(y, m, d + 9),
					// 	backgroundColor: "rgb(30,185,225)",
					// 	borderColor: "rgb(30,185,225)"
					// }, {
					// 	title: '2',
					// 	start: new Date(y, m, d + 13),
					// 	backgroundColor: "rgb(30,185,225)",
					// 	borderColor: "rgb(30,185,225)"
					// },
					// {
					// 	title: '3',
					// 	start: new Date(y, m, d + 17, 10, 30),
					// 	allDay: false,
					// 	backgroundColor: "rgb(30,185,225)",
					// 	borderColor: "rgb(30,185,225)"
					// },

				],
				editable: false,
				droppable: false, // this allows things to be dropped onto the calendar !!!

			});
		});
	}
	// 右侧统计图
	initCharts(sFundType) {
		let that = this;
		if (sFundType == 1) {
			new Promise((resolve, reject) => {
				this.homeService.getCharts(sFundType).subscribe(data => {
					if (data) {
						that.publicData = data;
						resolve(data);
					}
				})
			}).then(data => {
				var publicharts = echarts.init(document.getElementById('publicCharts'));
				publicharts.setOption({
					title: {
						text: '公募产品状态统计',
						subtext: '',
						x: 'center',
						textStyle: {
							color: 'rgb(0,80,150)',
							fontSize: "16"
						}
					},
					tooltip: {
						trigger: 'item',
						formatter: "{a} <br/>{b} : {c} ({d}%)"
					},
					legend: {
						orient: 'vertical',
						left: 'left',
						data: ['方案设计及立项', '准备报会', '已报会在审', '已获批', '已发行']
					},
					series: [
						{
							name: '产品状态',
							type: 'pie',
							radius: '55%',
							center: ['50%', '60%'],
							data: that.publicData,
							itemStyle: {
								emphasis: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					],
					color: ['rgb(0,80,150)', 'rgb(0,120,180)', 'rgb(30,185,225)', 'rgb(179,235,255)', 'rgb(150,150,150)', 'rgb(193,198,200)']
				})
			})
		} else if (sFundType == 2) {
			new Promise((resolve, reject) => {
				this.homeService.getCharts(sFundType).subscribe(data => {
					if (data) {
						that.otmData = data;
						resolve(data);
					}
				})
			}).then(data => {
				var otmcharts = echarts.init(document.getElementById('otmCharts'));
				otmcharts.setOption({
					title: {
						text: '一对多产品状态统计',
						subtext: '',
						x: 'center',
						textStyle: {
							color: 'rgb(0,80,150)',
							fontSize: "16"
						}
					},
					tooltip: {
						trigger: 'item',
						formatter: "{a} <br/>{b} : {c} ({d}%)"
					},
					legend: {
						orient: 'vertical',
						left: 'left',
						data: ['未成立', '已成立', '已终止']
					},
					series: [
						{
							name: '产品状态',
							type: 'pie',
							radius: '55%',
							center: ['50%', '60%'],
							data: that.otmData,
							itemStyle: {
								emphasis: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					],
					color: ['rgb(0,80,150)', 'rgb(0,120,180)', 'rgb(30,185,225)']
				})
			})
		} else if (sFundType == 3) {
			new Promise((resolve, reject) => {
				this.homeService.getCharts(sFundType).subscribe(data => {
					if (data) {
						that.otoData = data;
						resolve(data);
					}
				})
			}).then(data => {
				var otocharts = echarts.init(document.getElementById('otoCharts'));
				otocharts.setOption({
					title: {
						text: '一对一产品状态统计',
						subtext: '',
						x: 'center',
						textStyle: {
							color: 'rgb(0,80,150)',
							fontSize: "16"
						}
					},
					tooltip: {
						trigger: 'item',
						formatter: "{a} <br/>{b} : {c} ({d}%)"
					},
					legend: {
						orient: 'vertical',
						left: 'left',
						data: ['未成立', '已成立未运作', '已成立已运作', '已终止']
					},
					series: [
						{
							name: '产品状态',
							type: 'pie',
							radius: '55%',
							center: ['50%', '60%'],
							data: that.otoData,
							itemStyle: {
								emphasis: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					],
					color: ['rgb(0,80,150)', 'rgb(0,120,180)', 'rgb(30,185,225)', 'rgb(179,235,255)']
				})
			})
		}
	}
	// 下方折线图
	initeCharts() {
		let that = this;
		new Promise((resolve, reject) => {
			this.homeService.geteCharts().subscribe(data => {
				if (data) {
					that.lineData = data;
					that.lineData.map(function (item) {
						that.lineDataKey.push(item[0]);
						that.lineDataValue.push(item[1]);
					})
					resolve(data);
				}
			})
		}).then(data => {
			// setTimeout(function () {
			// 下方echarts
			var myChart = echarts.init(document.getElementById('bottomCharts'));
			var option = {
				visualMap: [{
					show: false,
					type: 'continuous',
					seriesIndex: 0,
					dimension: 0,
					min: 0,
					max: that.lineDataKey.length - 1
				}],
				title: [{
					top: '5%',
					left: 'center',
					text: '',
					textStyle: {
						color: 'rgb(0,80,150)',
						fontSize: "16"
					}
				}],
				tooltip: {
					trigger: 'axis'
				},
				xAxis: [{
					data: that.lineDataKey,
					gridIndex: 0,
					name: '年份',
				}],
				yAxis: [{
					splitLine: { show: false },
					gridIndex: 0,
					name: '数量（个）'
				}],
				grid: [{
					bottom: '30px'
				}, {
					top: '10px'
				}],
				series: [{
					type: 'line',
					showSymbol: false,
					data: that.lineDataValue,
					xAxisIndex: 0,
					yAxisIndex: 0,
					itemStyle: {
						normal: {
							lineStyle: {
								color: 'rgb(0,80,150)'
							}
						}
					}
				}]
			};
			// 加载下方折现图
			myChart.setOption(option);
			// }, 300);
		})
	}
}

